namespace BM.Tools.WebControls.MForm.Generator
{
    using System.Collections.ObjectModel;
    using System.Xml.Schema;

    using BM.Tools.Xml.Schema;

    /// <summary>
    /// FormVisited is a base class for all visited objects in the <see cref="FormBuilder" />.
    /// </summary>
    public class FormVisited : Visited
    {        
        private Collection<FormItem> childrenItems;

        /// <summary>
        /// Initializes a new instance of the <see cref="FormVisited"/> class. 
        /// </summary>
        /// <param name="builder">
        /// The builder.
        /// </param>
        /// <param name="parent">
        /// The parent.
        /// </param>
        /// <param name="schemaObject">
        /// The schemaObject.
        /// </param>
        public FormVisited(FormBuilder builder, Visited parent, XmlSchemaObject schemaObject) : base(parent, schemaObject, builder)
        {
        }

        /// <summary>
        /// Gets ChildrenItems.
        /// </summary>
        /// <value>
        /// The children items.
        /// </value>
        public virtual Collection<FormItem> ChildrenItems
        {
            get
            {
                if (childrenItems == null)
                {
                    CalculateChildrenItems();
                }

                return childrenItems;
            }
        }

        /// <summary>
        /// Gets FormItem.
        /// </summary>
        /// <value>
        /// The form item.
        /// </value>
        public FormItem FormItem
        {
            get
            {
                var item = this as FormItem;
                if (item != null)
                {
                    return item;
                }

                return ((FormVisited)parent).FormItem;
            }
        }

        /// <summary>
        /// Searches for all those children that are of <see cref="FormItem" /> type
        /// </summary>
        internal void CalculateChildrenItems()
        {
            childrenItems = new Collection<FormItem>();
            foreach (FormItem fi in GetChildren(typeof(FormItem)))
            {
                childrenItems.Add(fi);
            }
        }
    }
}